import router from "@/router";
import type { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from "vue-router";
import { AdminTitle, whiteRouterList } from "@/config";
import stroe from "@/store"
import { authModelUse } from "@/store/module/AuthModel";
import { userModelUse } from "@/store/module/UserModel";
import { permissionModelUse } from "@/store/module/permission";

router.beforeEach( async (to: RouteLocationNormalized, form: RouteLocationNormalized, next: NavigationGuardNext )=>{
  // 设置浏览器当前页面名称 拼凑当前页面信息
  document.title = AdminTitle + String(to.meta.name);

  // 存储当前节点的浏览记录
  let stores = authModelUse(stroe);
  stores.commit('setHistoryList', to);

  // 隶属于白名单的页面直接进入页面
  if(whiteRouterList.includes(to.path)){
    next();
  }
  

  // 权限分发
  let userModule = userModelUse(stroe);
  let permissionModule = permissionModelUse(stroe);
  let bwTicket = localStorage.getItem('bwTicket');
  let menuList = localStorage.getItem('menuList');

  // 如果用户登陆成功进行权限分发和过滤的逻辑
  if(bwTicket){
    // 将vuex存储的权限列表作为判断，防止重复添加路由
    if(userModule.state.menuListOld.length == 0){
      // 本地缓存中存储了用户信息
      if(menuList){
        userModule.commit('setMenuListOld', JSON.parse(menuList));
      }else{
        // 如果没存储则直接发送请求获取权限菜单
        await userModule.dispatch('getUserInfo');
      }
      // 如果权限菜单的列表是空值则踢回登录页面
      if(userModule.state.menuListOld.length == 0){ next('/') };

      // 登录完成获取到完整的权限菜单以后进行权限筛选
      permissionModule.commit('GenerateRoutes', userModule.state.menuListOld )
      
      // 将符合权限的权限菜单添加到路由中(api变更 需要手动循环导入)
      permissionModule.state.dynamicRoutes.forEach((route: RouteRecordRaw)=>{
        router.addRoute(route)
      })

      // 然后跳转到你要进入的路由
      next({...to, replace: true})
    }else{
      next()
    } 
  }else{
    // 如果不在白名单中，且没有token信息 则直接踢到登录页面
    next('/')
  }
})
  



